const db = require('../Mysql/sql')
const dayjs = require('dayjs')
const {
	nanoid
} = require('nanoid');

//店铺相关
const store = {
	//根据用户获取店铺信息
	getUseridStoreInfo(req, res) {
		const sql =
			`select s.*,u.username from store s,users u where s.userid=u.userid and s.userid=${req.auth.userid}`
		db.query(sql, [], (err, results) => {
			if (err) return res.cc(err)
			res.cc('获取成功', 200, results)
		})
	},
	//新增店铺
	addUseridStoreInfo(req, res) {
		req.body.userid = req.auth.userid

		const sql = `insert into store set ?`
		db.query(sql, req.body, (err, results) => {
			if (err) return res.cc(err)
			if (results.affectedRows !== 1) return res.cc('添加失败')
			res.cc('添加成功', 200)
		})
	},
	//删除店铺
	delUseridStoreInfo(req, res) {
		const sql = `delete from store where id=? and userid = ${req.auth.userid}`
		db.query(sql, req.body.id, (err, results) => {
			if (err) return res.cc(err)
			if (results.affectedRows !== 1) return res.cc('删除失败')
			res.cc('删除成功', 200)
		})
	},
	//修改店铺信息
	updateUseridStoreInfo(req, res) {
		const sql = `update store set ? where userid = ${req.auth.userid} and id=${req.body.id}`
		db.query(sql, req.body, (err, results) => {
			if (err) return res.cc(err)
			if (results.affectedRows !== 1) return res.cc('修改失败')
			res.cc('修改成功', 200)
		})
	},
}

//商品相关
const goods = {
	//根据店铺id新增商品
	setGoodsByStoreid(req, res) {
		const {
			id,
			submitList,
			...info
		} = req.body
		const sql = `insert into store_products set ?`
		db.query(sql, info, (err, results) => {
			if (err) return res.cc(err)
			if (results.affectedRows !== 1) return res.cc('添加失败')
			const str = (arr) => {
				let value = ''
				for (let i in arr) {
					value = value +
						`(${arr[i].sku_id},${arr[i].goods_stock||0},${arr[i].goods_price||0},"${arr[i].goods_img||''}",${results.insertId},'${JSON.stringify(arr[i].properties)}'),`
				}
				return value
			}
			let arr = str(submitList)
			const sql2 = `insert sku(sku_id,goods_stock,goods_price,goods_img,goods_id,properties)
			values ${arr.slice(0, -1)} on DUPLICATE KEY UPDATE 
			sku_id=values(sku_id),
			goods_stock=values(goods_stock),
			goods_price=values(goods_price),
			goods_img=values(goods_img),
			goods_id=values(goods_id),
			properties=values(properties)
			`
			db.query(sql2, [], (err2, results2) => {
				if (err2) return res.cc(err2)
				res.cc('添加成功', 200)
			})
		})

	},
	delCoodsSkuById() {
		const sql = `delete from sku where id = ${req.body.id}`
		db.query(sql, info, (err, results) => {
			if (err) return res.cc(err)
			if (results.affectedRows !== 1) return res.cc('删除失败')
			res.cc('删除成功', 200)
		})
	},

	//根据店铺id修改商品sku
	updateGoodsByStoreid(req, res) {
		const str = (arr) => {
			let value = ''
			for (let i in arr) {
				value = value +
					`(${arr[i].sku_id||0},${arr[i].goods_stock||0},${arr[i].goods_price||0},"${arr[i].goods_img||''}",${arr[i].goods_id},'${JSON.stringify(arr[i].properties)}'),`
			}
			return value
		}
		const {
			id,
			submitList,
			...info
		} = req.body
		let arr = str(submitList)
		const sql3 = `delete from sku where goods_id = ${id}`
		const sql2 = `insert sku(sku_id,goods_stock,goods_price,goods_img,goods_id,properties) 
		values ${arr.slice(0, -1)} on DUPLICATE KEY UPDATE 
		sku_id=values(sku_id),
		goods_stock=values(goods_stock),
		goods_price=values(goods_price),
		goods_img=values(goods_img),
		goods_id=values(goods_id),
		properties=values(properties)
		`

		const sql = `update store_products s set ? where id=${id}`
		db.query(sql, info, (err, results) => {
			console.log(info)
			if (err) return res.cc(err)
			if (results.affectedRows !== 1) return res.cc('修改失败')
			if (!submitList.length) res.cc('修改成功', 200)
			db.query(sql3, [], (err3, results3) => {
				if (err3) return res.cc(err3)
				db.query(sql2, [], (err2, results2) => {
					if (err2) return res.cc(err2)
					res.cc('修改成功', 200)
				})
			})

		})
	},
	//获取商品参数
	getGoodListAttr(req, res) {
		let sql = `select * from sku where goods_id=?`
		db.query(sql, req.query.id, (err, results) => {
			if (err) return res.cc(err)
			res.cc('获取成功', 200, results)
		})
	},
	//根据店铺id获取商品列表
	getGoodsListByStoreid(req, res) {
		const sql = `select s.*,st.store_name,st.area,st.logo,st.address,st.userid,d2.text type_name,d.text breed_name from store_products s
		left join dictionary d on s.breed = d.nid
		left join dictionary d2 on s.type = d2.nid
		left join store st on s.store_id = st.id
		where 1=1
		${req.query.id?`and s.id=${req.query.id}`:``}
		${req.query.store_id?`and s.store_id=${req.query.store_id}`:``}
		${req.query.breed?`and s.breed like '%${req.query.breed}%'`:``}
		${req.query.searchValue?`and s.title like '%${req.query.searchValue}%' or s.name like '%${req.query.searchValue}%'`:``}
		`
		db.query(sql, [], (err, results) => {
			if (err) return res.cc(err)
			res.cc('获取成功', 200, results)
		})
	},
	//删除商品
	delGoodsByStoreid(req, res) {
		const sql = `delete from store_products where id = ${req.body.id}`
		db.query(sql, [], (err, results) => {
			if (err) return res.cc(err)
			if (results.affectedRows !== 1) return res.cc('删除失败')
			res.cc('删除成功', 200)
		})
	}
}

//支付相关
const order = {
	//生成订单
	//订单状态 status 0=全部 1=待支付 2=待发货 3=待收货 4=待评价 5=退款/售后
	async generateOrder(req, res) {
		let body = req.body
		let orderid = nanoid()
		let createTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
		let status = 1
		let store_id = body.store_id || null
		const mongodb = res.mongodb
		const collection = mongodb.collection('user_order')

		if (store_id) { // 多个购买
			// body.store_id

		} else { //单个
			const sql = `select st.store_name, s.*,sku.goods_price,sku.goods_img,sku.properties from store_products s,sku,store st
			where s.id=${body[0].goods_id} and sku.sku_id = ${body[0].sku_id} and st.id = s.store_id`
			//库存修改
			const sql2 =
				`update sku set goods_stock=goods_stock-${body[0].count} where sku_id=${body[0].sku_id}`
			db.query(sql, [], (err, results) => {
				if (err) return res.cc(err)
				if (!results.length) return res.cc('没有该商品')
				db.query(sql2, [], (err2, results2) => {
					if (err2) return res.cc(err2)
					const mergedArr = results.map(item1 => {
						const item2 = body.find(item2 => item2.goods_id == item1.id);
						return item2 ? {
							...item1,
							...item2
						} : item1;
					})
					let total_price = 0,
						coupon_price = 0,
						express_fee = 0
					mergedArr.map(v => {
						total_price += ((v.goods_price) * (v.count))
						coupon_price += ((v.goods_price) * (v.count))
						express_fee += v.express_fee
					})
					let data = {
						orderid,
						createTime,
						status,
						total_price,
						coupon_price: coupon_price + express_fee,
						express_fee,
						goods_list: mergedArr,
						userid: req.auth.userid,
						addr_id: body[0].addr_id
					}
					collection.insertOne(data)
					res.cc('下单成功', 200, orderid)
				})

			})
		}
	},
	//获取订单详情
	async getOrderDetail(req, res) {
		let query = req.query
		const mongodb = res.mongodb
		const collection = mongodb.collection('user_order')
		const findResult = await collection.find({
			orderid: query.orderid
		}).toArray();
		if (!findResult.length) return res.cc('没有该订单')
		res.cc('获取成功', 200, findResult[0])
	},
	//获取订单列表
	async getOrderList(req, res) {
		let query = req.query
		const mongodb = res.mongodb
		const collection = mongodb.collection('user_order')
		let findResult = []
		if (Number(query.status)) {
			findResult = await collection.find({
				status: Number(query.status)
			}).toArray()
		} else {
			findResult = await collection.find({}).toArray()
		}
		res.cc('获取成功', 200, findResult)
	},
	//修改订单信息
	async setOrderDetail(req, res) {
		let body = req.body
		const {
			orderid,
			...info
		} = body
		const mongodb = res.mongodb
		const collection = mongodb.collection('user_order')
		await collection.updateOne({
			orderid: body.orderid
		}, {
			$set: {
				...info
			}
		})
		res.cc('修改成功', 200)
	},
	//加入购物车
	async joinShoppingCart(req, res) {
		let body = req.body
		body.purchaser_id = req.auth.userid
		const sql = `select sku.goods_price,sku.goods_img,sku.properties from sku
		where sku.sku_id = ${body.sku_id}`
		const mongodb = res.mongodb
		const collection = mongodb.collection('shopping_cart')
		let findResult = await collection.find({
			purchaser_id: body.purchaser_id,
			store_id: body.store_id
		}).toArray()
		db.query(sql,(err,results) => {
			if(err) return res.cc(err)
			if(!results.length) res.cc('暂无商品数据')
			body = {...body,...results[0]}
			if (findResult.length) { //数量＋1
				let state = false
				findResult[0].goods_list.map(v => {
					if (v.sku_id == body.sku_id) {
						v.count += body.count
						state = true
					}
				})
				let goods_list = state ? [...findResult[0].goods_list] : [...findResult[0].goods_list, body]
				collection.updateOne({
					purchaser_id: body.purchaser_id,
					store_id: body.store_id
				}, {
					$set: {
						store_id: findResult[0].store_id,
						store_name: findResult[0].store_name,
						purchaser_id: findResult[0].purchaser_id,
						goods_list: goods_list
						// count: findResult[0].count + body.count
					}
				})
			} else {
				let info = {
					store_id: body.store_id,
					store_name: body.store_name,
					purchaser_id: body.purchaser_id,
					goods_list: [body]
				}
				collection.insertOne(info)
			}
			// count
			res.cc('加入成功', 200)
		})
		
	},
	//购物车列表
	async getShoppingCart(req, res) {
		let body = req.body
		const mongodb = res.mongodb
		const collection = mongodb.collection('shopping_cart')
		let findResult = await collection.find({
			purchaser_id: req.auth.userid
		}).toArray()
		res.cc('获取成功', 200, findResult)
	},

	//余额支付
	async orderPay(req, res) {
		let body = req.body
		body.payTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
		body.status = 2
		const mongodb = res.mongodb
		const collection = mongodb.collection('user_order')
		const findResult = await collection.find({
			orderid: body.orderid
		}).toArray();
		if (findResult[0].status !== 1) return res.cc('请勿重复支付')
		//支付
		let sql = `select balance from users where userid=${req.auth.userid}`
		let sql2 =
			`update users set balance=balance-${findResult[0].coupon_price} where userid=${req.auth.userid}`
		db.query(sql, [], (err, results) => {
			if (err) return res.cc(err)
			if (results[0].balance < findResult[0].coupon_price) return res.cc('余额不足')
			db.query(sql2, [], (err2, results2) => {
				if (err2) return res.cc(err2)
				collection.updateOne({
					orderid: body.orderid
				}, {
					$set: {
						...findResult[0],
						...body
					}
				})
				res.cc('支付成功', 200)
			})
		})
	},
	//发货
	sendGoods(req, res) {
		let body = req.body
		body.status = 3
	},
	//收货
	putGoods(req, res) {
		let body = req.body
		body.status = 4
	},
	//评价
	evaluateCoods(req, res) {
		let body = req.body
		body.status = 5
	},
	//退款
	refundCoods(req, res) {
		let body = req.body
		body.status = 5
	}

}

//收货地址
const addr = {
	async getUserAddress(req, res) {
		let body = req.body
		const collection = res.mongodb.collection('user_addr')
		const findResult = await collection.find({
			userid: req.auth.userid,
			...body
		}).sort({
			is_default: -1
		}).toArray()
		res.cc('获取成功', 200, findResult)
	},
	/* 
		收货人 consignee
		省市区街道 province city area street
		详细地址	detail_addr
		是否默认	is_default 1默认
		手机号 phone
		userid
	 */
	async addUserAddress(req, res) {
		let body = req.body
		let id = nanoid()
		const collection = res.mongodb.collection('user_addr')
		await collection.insertOne({
			...body,
			id,
			userid: req.auth.userid
		})
		res.cc('添加成功', 200, id)
	},
	async updateUserAddress(req, res) {
		let body = req.body
		const {
			id,
			...info
		} = body
		const collection = res.mongodb.collection('user_addr')
		if (body.is_default) {
			await collection.updateMany({
				userid: req.auth.userid
			}, [{
				$set: {
					is_default: false
				}
			}])
		}
		await collection.updateOne({
			id: body.id
		}, {
			$set: {
				...info
			}
		})
		res.cc('修改成功', 200)
	},
	delUserAddress(req, res) {
		const collection = res.mongodb.collection('user_addr')
		collection.deleteOne({
			id: req.body.id
		})
		res.cc('删除成功', 200)
	},
}
module.exports = {
	...store,
	...goods,
	...order,
	...addr
}